
<template>
  <div class="AddOrUpdate_main add_container">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="表单类型" prop="formTypeCode">
          <span>{{ formData.formTypeCode }}</span>
        </el-form-item>
        <el-form-item label="表单编码" prop="formCode">
          <span>{{ formData.formCode }}</span>
        </el-form-item>
        <el-form-item label="入库人员">
          <div>{{ formData.inByRealName }}</div>
        </el-form-item>
        <el-form-item label="入库时间" class="time">
          <span>{{ formData.inTime }}</span>
        </el-form-item>
        <el-form-item label="备注" class="remark">
          <span>{{ formData.remark }}</span>
        </el-form-item>
      </el-form>
      <!-- <div class="spare-btn">
        <el-button
          class="esc"
          @click.stop="addSparePartsMaterials"
        >选择备件信息</el-button>
        <el-button
          class="esc"
          @click.stop="importData"
        >导 入</el-button>
      </div> -->
      <div ref="table_container2" class="table_container addRow_table">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
        >
          <el-table-column
            prop="code"
            label="备件编码"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="备件名称"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="model"
            label="规格型号"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.model }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="batch"
            label="批号"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.batch }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="numberUnitLabel"
            label="备件单位"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.numberUnitLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="备件单价(元)"
            placeholder="请输入"
            clearable
            width="100"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="number"
            label="入库数量"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseName" label="仓库" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.warehouseName }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getUserList, importMethod } from '@/api/equipmentManage/sparePart/warehousing'
import addMaterials from '../../sparePartsManagement/sparePartsInfo/chooseSparePartsInfo.vue'
import chooseWarehouse from '../sparePartsWarehouse/chooseWarehouse.vue'
import ImportData from '@/components/JLink/common/ImportData'
import { list } from '@/api/equipmentManage/sparePart/warehouse'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        status: '1',
        companyId: undefined,
        formTypeCode: '',
        formCode: '',
        inBy: '',
        inTime: '',
        remark: ''
      },
      pageId: '备件入库',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      typeList: [
        { value: 1, label: '采购入库' },
        { value: 2, label: '外协入库' },
        { value: 3, label: '成品入库' }
      ],
      selectData: [],
      tableData: [],
      tableHeight: '300',
      num: 1,
      roleOptions: [],
      rules: {
        formTypeCode: [
          { required: true, message: '表单类型不能为空', trigger: 'change' }
        ],
        formCode: [
          { required: true, message: '表单编码不能为空', trigger: 'blur' }
        ]
      },
      objectData: [],
      userList: [],
      rowIndex: undefined
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getList()
    this.laodUserList()
    console.log(this.userId)
    this.formData.inBy = this.userId
    this.formData.inTime = moment(new Date()).format('YYYY-MM-DD HH:mm')
  },
  methods: {
    importData() { // 导入
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.data) {
          res.data.forEach(item => {
            this.addRow(item)
          })
        }
      })
    },
    addRow(row) {
      const row2 = [
        {
          code: row.spareCode || '',
          name: row.spareName || '',
          model: row.spareModel || '',
          batch: row.batch || '',
          numberUnitLabel: row.numberUnitLabel || '',
          price: row.price || '',
          number: row.number || '',
          warehouseName: row.deviceSpareWarehouseName || '',
          deviceSpareStandingBookId: row.deviceSpareStandingBookId || '',
          deviceSpareWarehouseId: row.deviceSpareWarehouseId || ''
        }
      ]
      this.tableData.push(...row2)
    },
    laodUserList() {
      getUserList({
        companyId: this.$store.state.companyId
      }).then(res => {
        console.log(res)
        this.userList = res.data
      })
    },
    getList() {
      list(this.pageData).then(res => {
        this.selectData = res.data
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData.companyId = res.company.companyId
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        //   this.stockList = res.data.data
        })
      })
    },
    // 校验整数
    onlyInteger(e, index) {
      const rule = /^[0-9][0-9]*$/
      const num = Number(e)
      if (rule.test(e)) {
        this.tableData[index].number = e
      } else if (e && num !== 0) {
        this.$message.warning('入库数量必须为整数')
        this.tableData[index].number = e.replace('.', '')
      }
    },
    // // 保留两位小数
    // haveTwoDecimalPlaces(e, index) {
    //   console.log(this.tableData[index])
    //   if (e.indexOf('.') > -1) {
    //     const afterPoint = e.split('.')
    //     if (e !== 0 && afterPoint[1].length > 2) {
    //       this.tableData[index].price = e.slice(0, e.indexOf('.') + 3)
    //       this.$message.warning('至多可输入两位小数')
    //     } else if (e == 0) {
    //       this.tableData[index].price = 0
    //     }
    //   } else {
    //     this.tableData[index].price = e
    //   }
    // },
    // 提交
    onSubmit() {
      console.log(this.formData)
      if (!this.tableData || this.tableData.length == 0) {
        this.$message.warning('请选择备件信息')
        return false
      } else {
        this.$refs['form'].validate(valid => {
          if (this.tableData.some((e) => this.tableData.filter((e1) => e1.batch == e.batch).length > 1 && e.batch)) {
            this.$message.warning('批号不可重复填写,请重新填写批号')
            return false
          } else if (this.tableData.some((e) => !e.warehouseName)) {
            this.$message.warning('仓库不能为空')
            return false
          } else if (this.tableData.some((e) => !e.number)) {
            this.$message.warning('入库数量不能为空')
            return false
          } else if (this.tableData.some((e) => !e.price)) {
            this.$message.warning('备件单价不能为空')
            return false
          } else {
            if (valid) {
              const data = this.tableData.map(item => {
                const obj = {
                  ...item,
                  ...this.formData
                }
                console.log(obj)
                return obj
              })
              console.log(data)
              addOrUpdate(data).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$layer.close(this.layerid) // 关闭弹框
                this.$parent.refresh() // 调用父组件的刷新方法
              })
            }
          }
        })
      }
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 移除行数据
    removeRow(index) {
      this.tableData.splice(index, 1)
    },
    // 选择仓库
    chooseWarehouses(row, index) {
      this.rowIndex = index
      console.log(row.deviceSpareWarehouseId)
      this.$layer.iframe({// 弹框
        content: {
          content: chooseWarehouse, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            warehouseId: row.deviceSpareWarehouseId ? row.deviceSpareWarehouseId : '',
            sparePartId: row.id
          }// props
        },
        area: ['880px', '570px'],
        title: '选择仓库', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择备件信息
    addSparePartsMaterials() {
      this.$layer.iframe({// 弹框
        content: {
          content: addMaterials, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
          }// props
        },
        area: ['880px', '570px'],
        title: '选择备件信息', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择物料后从弹窗取出来的数据
    addMaterial(data) {
      console.log(11111, data)
      this.tableData = this.tableData.concat(data)
    },
    // 拿到选择仓库的值
    showWarehouse(row, checked) {
      if (checked == false) {
        const arr = this.$deepClone(this.tableData)
        arr[this.rowIndex].deviceSpareWarehouseId = row.id
        arr[this.rowIndex].warehouseName = row.name
        console.log(this.tableData[this.rowIndex])
        this.$set(arr, 'warehouseName', row.name)
        this.tableData = arr
      } else {
        const arr = this.$deepClone(this.tableData)
        arr.forEach((item, index) => {
          item.deviceSpareWarehouseId = row.id
          item.warehouseName = row.name
          this.$set(item, 'warehouseName', row.name)
        })
        this.tableData = arr
      }
    }
  }
}
</script>

<style lang="less" scoped>
.table_container{
  padding-top: 20px;
}
.addRow_table{
  padding-left: 0px;
  padding-right: 0px;
}
</style>
